package handler

import (
	"net/http"
	"runtime"
	"runtime/debug"
	"time"

	"github.com/gin-gonic/gin"
	"goserver/internal/middleware"
)

// MetricsHandler 性能指标处理器
type MetricsHandler struct {
	collector *middleware.MetricsCollector
}

// NewMetricsHandler 创建性能指标处理器
func NewMetricsHandler(collector *middleware.MetricsCollector) *MetricsHandler {
	return &MetricsHandler{
		collector: collector,
	}
}

// RegisterRoutes 注册路由
func (h *MetricsHandler) RegisterRoutes(r *gin.Engine) {
	metrics := r.Group("/metrics")
	{
		metrics.GET("/", h.collector.GetMetrics())
		metrics.POST("/reset", h.collector.ResetMetrics())
		metrics.GET("/health", h.healthCheck)
		metrics.GET("/memory", h.memoryStats)
		metrics.GET("/gc", h.triggerGC)
		metrics.GET("/goroutines", h.goroutineStats)
		metrics.GET("/cpu", h.cpuStats)
	}
}

// healthCheck 健康检查
func (h *MetricsHandler) healthCheck(c *gin.Context) {
	c.JSON(http.StatusOK, gin.H{
		"status": "healthy",
		"time":   time.Now().Format(time.RFC3339),
	})
}

// memoryStats ��存统计
func (h *MetricsHandler) memoryStats(c *gin.Context) {
	var stats runtime.MemStats
	runtime.ReadMemStats(&stats)

	c.JSON(http.StatusOK, gin.H{
		"heap_alloc":       stats.HeapAlloc,
		"heap_sys":         stats.HeapSys,
		"heap_idle":        stats.HeapIdle,
		"heap_inuse":       stats.HeapInuse,
		"heap_released":    stats.HeapReleased,
		"heap_objects":     stats.HeapObjects,
		"gc_num":           stats.NumGC,
		"gc_pause_ns":      stats.PauseNs[(stats.NumGC+255)%256],
		"gc_pause_total":   stats.PauseTotalNs,
		"num_goroutines":   runtime.NumGoroutine(),
		"memory_allocated": stats.Alloc,
		"memory_total":     stats.TotalAlloc,
		"memory_sys":       stats.Sys,
		"next_gc":          stats.NextGC,
	})
}

// triggerGC 触发垃圾回收
func (h *MetricsHandler) triggerGC(c *gin.Context) {
	before := time.Now()
	runtime.GC()
	debug.FreeOSMemory()
	duration := time.Since(before)

	var stats runtime.MemStats
	runtime.ReadMemStats(&stats)

	c.JSON(http.StatusOK, gin.H{
		"message":        "GC triggered successfully",
		"duration":       duration.String(),
		"heap_released": stats.HeapReleased,
		"heap_objects":  stats.HeapObjects,
		"next_gc":       stats.NextGC,
	})
}

// goroutineStats Goroutine统计
func (h *MetricsHandler) goroutineStats(c *gin.Context) {
	c.JSON(http.StatusOK, gin.H{
		"num_goroutines": runtime.NumGoroutine(),
		"num_cpu":        runtime.NumCPU(),
		"num_cgo_call":   runtime.NumCgoCall(),
		"max_procs":      runtime.GOMAXPROCS(0),
	})
}

// cpuStats CPU统计
func (h *MetricsHandler) cpuStats(c *gin.Context) {
	var stats runtime.MemStats
	runtime.ReadMemStats(&stats)

	c.JSON(http.StatusOK, gin.H{
		"num_cpu":     runtime.NumCPU(),
		"num_procs":   runtime.GOMAXPROCS(0),
		"cgo_calls":   runtime.NumCgoCall(),
		"gc_cpu_fraction": stats.GCCPUFraction,
		"os":         runtime.GOOS,
		"arch":       runtime.GOARCH,
		"go_version": runtime.Version(),
	})
} 